package web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import dao.UserDAO;
import domain.User;

/**
 * General attributes.
 * 
 * @author Diogo Anderson
 * @author Felipe Sampaio
 * @author Vinicius Cavalcanti
 */
public class UserAction extends ActionSupport implements ModelDriven<User> {

	private static final long serialVersionUID = 1L;
	private User user = new User();
	private UserDAO dao = new UserDAO();
	private List<User> userList = new ArrayList<User>();

	@Override
	public User getModel() {
		return user;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String saveOrUpdate() {
		
		System.out.println("ENTROU SAVE");
		if (dao.saveOrUpdate(user)) {
			userList = dao.listUser();
			return SUCCESS;
		}
		return ERROR;
	}

	public String list() {
		userList = dao.listUser();
		return SUCCESS;
	}

	// public String usersByName(){
	//		
	// HttpServletRequest request = ServletActionContext.getRequest();
	// List<String> names = dao.getUserNames(request.getParameter("q"));
	//		
	// for (String name : names) {
	// this.names += name + "\n";
	// }
	// return SUCCESS;
	// }

	public String delete() {
		HttpServletRequest request = (HttpServletRequest) ActionContext
				.getContext().get(ServletActionContext.HTTP_REQUEST);
		dao.deleteUser(Long.parseLong(request.getParameter("id")));
		return SUCCESS;
	}

	public String edit() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		setUser(dao.listUserById(Long.parseLong(request.getParameter("id"))));
		return SUCCESS;
	}
	
	public String showUser() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		setUser(dao.listUserById(Long.parseLong(request.getParameter("id"))));
		return SUCCESS;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
}
